package com.eslserver.action.dropdown;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.aware.ScheduleAware;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.dao.ScheduleDAO;
import com.eslserver.to.ESL;
import com.eslserver.to.Image;
import com.eslserver.to.Schedule;
import com.eslserver.to.wrapper.ImageWrapper;
import com.eslserver.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class ImageDropdownServlet extends HttpServlet implements ScheduleAware {
	public static final Logger LOG = LoggerFactory
			.getLogger(ImageDropdownServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String eslID = null;
		Integer imageID = 0;

		PrintWriter writer = resp.getWriter();

		try {
			ScheduleDAO scheduleDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getScheduleDAO();
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();

			String scheduleID = req.getParameter(PARAM_SCHEDULE_ID);
			if (scheduleID != null && scheduleID.length() > 0) {
				if (Integer.valueOf(scheduleID) != 0) {
					Schedule schedule = scheduleDAO.loadSchedule(Integer
							.valueOf(scheduleID));
					imageID = schedule != null ? schedule.getImage()
							.getImageID() : imageID;
				}
			}

			if (req.getParameter(PARAM_ESL_ID) != null
					&& req.getParameter(PARAM_ESL_ID).length() > 0) {
				eslID = req.getParameter(PARAM_ESL_ID);
			}

			Map<Integer, String> imageMap = new HashMap<Integer, String>();
			ESL esl = eslDAO.loadESL(Integer.valueOf(eslID));
			for (Image image : esl.getImages()) {
				ImageWrapper imageWrapper = ImageWrapper
						.createESLImageWrapper(image);
				imageMap.put(imageWrapper.getImageID(), imageWrapper.getName());
			}

			writer.println(JSONResponseUtil
					.getJSONObjectString(new ImageDropdownWrapper(imageMap,
							imageID)));

		} catch (DAOException e) {
			LOG.error("error laoding ESLs", e);
		}

	}

	private class ImageDropdownWrapper {
		Map<Integer, String> imageMap;
		Integer imageID;

		public ImageDropdownWrapper(Map<Integer, String> imageMap,
				Integer imageID) {
			this.imageMap = imageMap;
			this.imageID = imageID;
		}
	}
}
